package com.a01_2021.thousandstimes.config;

import com.baomidou.dynamic.datasource.provider.AbstractJdbcDataSourceProvider;
import com.baomidou.dynamic.datasource.provider.DynamicDataSourceProvider;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DataSourceProperty;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author E1xP@foxmail.com
 * @Version 1.0
 * @PACKAGE_NAME com.a01_2021.thousandstimes.config
 * @CLASS_NAME MybatisPlusConfig
 * @Description TODO Mybatis-plus配置
 * @Date 2021/2/22 下午 4:09
 **/
@EnableTransactionManagement
@Configuration
public class MybatisPlusConfig {
    @Value("${spring.datasource.username}")
    private String USERNAME;    //数据库用户名
    @Value("${spring.datasource.password}")
    private String PASSWORD;    //数据库密码
    @Value("${spring.datasource.url}")
    private String HEADURL;     //数据库URL
    @Value("${spring.datasource.driver-class-name}")
    private String DRIVER;      //数据库驱动类

    /**
     * 动态配置数据库源
     *
     * @return 返还数据库map
     */
    @Bean
    public DynamicDataSourceProvider dynamicDataSourceProvider(){
        return new AbstractJdbcDataSourceProvider(DRIVER
                ,HEADURL,USERNAME,PASSWORD) {
            @Override
            protected Map<String, DataSourceProperty> executeStmt(Statement statement) throws SQLException {
                //查询
                ResultSet rs = statement.executeQuery("select * from thousandstimes.sys_instance");
                Map<String, DataSourceProperty> map = new HashMap<>();

                //连接主数据库
                DataSourceProperty property = new DataSourceProperty();
                property.setUsername(USERNAME);
                property.setPassword(PASSWORD);
                property.setUrl(HEADURL + "thousandstimes");
                property.setDriverClassName(DRIVER);
                map.put("master", property);

                //根据租户表连接数据库
                while (rs.next()) {
                    String id = rs.getString("id");
                    String name = rs.getString("name");
                    String url = HEADURL + name;
                    DataSourceProperty propertyItem = new DataSourceProperty();
                    propertyItem.setUsername(USERNAME);
                    propertyItem.setPassword(PASSWORD);
                    propertyItem.setUrl(url);
                    propertyItem.setDriverClassName(DRIVER);
                    map.put(id, propertyItem);
                }
                return map;
            }
        };
    }
}
